package tech.aistar.controller;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.aistar.model.pojo.Group1;
import tech.aistar.model.pojo.Group2;
import tech.aistar.model.pojo.Result;
import tech.aistar.model.pojo.Users;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/4/29 2:37 下午
 */
@Controller
@RequestMapping("/user")
public class RegisterController {

    @GetMapping("/register")
    public String register(){
        return "user/register";
    }

    @PostMapping("/reg")
    @ResponseBody
    public Result register(@Validated(Group2.class) Users user, BindingResult bindingResult){

        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();

        Map<String,String> errorsMap = new HashMap<>();

        if(null!=fieldErrorList && fieldErrorList.size()>0){
            for (FieldError f : fieldErrorList) {
                System.out.print(f.getField()+"=>");
                System.out.println(f.getDefaultMessage());
                errorsMap.put(f.getField(),f.getDefaultMessage());
            }
            return new Result("500","注册失败",errorsMap);
        }
        return new Result("200","注册成功");
    }
}
